package cn.hacynn.nd.interceptor;

import cn.hacynn.nd.common.constant.MessageConstant;
import cn.hacynn.nd.common.context.BaseContext;
import cn.hacynn.nd.common.exception.UserLoginException;
import cn.hacynn.nd.common.properties.JwtProperties;
import cn.hacynn.nd.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author Hacynn
 * @Date 2024/5/25 15:34
 * @Version 1.0
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 校验jwt
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        //1. 从请求头中获取令牌
//        String cookieHeader = request.getHeader("Cookie");
//        String token = null;
//        if (cookieHeader != null) {
//            String[] cookies = cookieHeader.split("; ");
//            for (String cookie : cookies) {
//                String[] parts = cookie.split("=");
//                if (parts.length == 2 && parts[0].equals("COOKIE-TOKEN")) {
//                    token = parts[1];
//                }
//            }
//        }
        Cookie[] cookies = request.getCookies();
        String token = null;
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //判断cookie中是否有和COOKIE-TOKEN相等的
                if ("COOKIE-TOKEN".equals(cookie.getName())) {
                    token = cookie.getValue();
                }
            }
        }

        //2. 校验令牌
        try {
            log.info("从请求头中获得jwt令牌: {}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            //获取当前claim中的用户id
            Long id = Long.valueOf(claims.get("id").toString());
            log.info("当前用户id: {}", id);
            // 存入BaseContext中
            BaseContext.setCurrentId(id);
            //3. 放行
            return true;
        } catch (Exception ex) {
            // 用户登录
            log.info("用户未登录，进行拦截！");
            response.setStatus(401);
            return false;
        }
    }
}
